*___________________________________________________________________________________________________

	VECM2(dsIn=, model=, order=1, nImpulse=12, LRCoeffOut=LRCoeff, CovOut=covInnovation,
	PrintLevel=2)

	macro to run a vector error correction model from quote data, using proc model.

	Parameters:
	dsIn		Input dataset (in form generated by the qBuild macro)
	model		Specification of price vector (e.g., p1 p2 p3).
	order		order of VECM
	nImpulse	How far ahead to forecast the impulse response function
				Note: the cumulative impulse response functions are output to a
				temporary dataset named 'pred'.
	LRCoeffOut	Output dataset with matric of long-run cumulative impact coefficients
	covOut		Output dataset with covariance matrix of innovations
	PrintLevel	Print detail.

____________________________________________________________________________________________________;
%macro VECM2(dsIn=, model=, order=1, nImpulse=12, LRCoeffOut=LRCoeff, CovOut=covInnovation,
	PrintLevel=2);
%do i=1 %to 10;
	%let p&i = %scan(&model, &i);
	%put &&p&i;
	%if %length(&&p&i)=0 %then %goto done1;
%end;
%done1: %let nPrice=%eval(&i-1);
%put nPrice=&nPrice;

data shock;
	length ShockedVariable $ 12.;
	%do iShock=1 %to &nPrice;
		ShockedVariable = "&&p&iShock";
		%do j=1 %to &nPrice;
			&&p&j = 0;
		%end;
		do i=1 to &order+1;
			output;
		end;
		&&p&iShock = 1;
		output;
		%do j=1 %to &nPrice;
			&&p&j = .;
		%end;
		do i=1 to &nImpulse;
			output;
		end;
	%end;
	run;

proc model data=&dsIn 
	%if &PrintLevel>=2 %then list;
	;

	*	Define price differences and cointegration vectors;
	%do i=1 %to &nPrice;
		d&&p&i = dif( &&p&i );
		%if &i>=2 %then %str(z&i = lag(&p1) - lag(&&p&i) - zmean&i;);
	%end;
	
	*	Build equations for each price;
	%do i=1 %to &nPrice;
		&&p&i = lag(&&p&i)
			%do j=1 %to &nPrice;
				%do k=1 %to &order;
					+ c_&&p&i.._&&p&j.._&k * lag&k(d&&p&j)
				%end;
				%*	Error correction term;
				%if &j>=2 %then %str(+ g_&&p&i.._&j * z&j);
			%end;
		;
	%end;

	*	estimate the model;
	fit &model / covs %if &PrintLevel=0 %then noprint;;
	%if %length(&CovOut)>0 %then ods output covResiduals=&CovOut;;
	run;

	*	set cointegration vector long run means to zero;
	%do i=2 %to &nPrice;
		zmean&i = 0;
	%end; 


	solve / forecast data=shock out=pred noprint;
	by notsorted ShockedVariable;
	run;
	quit;

data lrc;
	set pred;
	if _lag_<&nImpulse then delete;
	array vn(&nPrice) $;
	%do i=1 %to &nPrice;
		vn(&i) = "&&p&i";
	%end;
	keep ShockedVariable &model;
	run;
proc transpose data=lrc out=&LRCoeffOut name=Variable;
	id ShockedVariable;
	run;
%if &PrintLevel>=1 %then %do;
proc print data=&LRCoeffOut noobs;
	title2 "VECM2. Long-run (cumulative) impact coefficients (dataset=&LRCoeffOut)";
	run;
%end;
%exit:
	run;
%mend VECM2;


